package com.icesoft.base.manager.entity.security;

import com.icesoft.base.manager.model.MenuVo;
import com.icesoft.base.manager.suppose.NotUpdatePart;
import com.icesoft.core.dao.base.BaseModel;
import com.icesoft.core.dao.suppose.validation.UniqueCheck;
import com.icesoft.core.web.suppose.validation.ChineseOrEnglishOrNumber;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.*;

@Table(name = "qx_Menu", uniqueConstraints = @UniqueConstraint(columnNames = {"pid", "title"}), indexes = {
        @Index(columnList = "sort", name = "idx_menu_sort")})
@Entity
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Cacheable
public class SysMenu extends BaseModel {

    private String url;
    @Column(nullable = false, length = 10)
    @ChineseOrEnglishOrNumber
    @UniqueCheck(cascade = "pid", message = "同级的菜单标题已存在")
    private String title;
    @NotUpdatePart
    private int pid;
    @Column(length = 50)
    private String icon;
    @Column(nullable = false)
    private int sort;
    @Column(length = 10)
    private String target;

    private boolean disabled;

    public SysMenu(MenuVo menuVo) {
        super();
        this.pid = menuVo.getPid();
        this.url = menuVo.getHref();
        this.title = menuVo.getTitle();
        this.icon = menuVo.getIcon();
        this.target = menuVo.getTarget();
    }

    public SysMenu() {
    }

    @PrePersist
    protected void prePersist() {
        preUpdate();
    }

    @PreUpdate
    protected void preUpdate() {
        if (StringUtils.isBlank(url)) {
            url = null;
        }
        if (StringUtils.isBlank(icon)) {
            icon = null;
        }
    }
}
